const { v4: uuidv4 } = require("uuid");
const bcrypt = require("bcryptjs");
const { query, withTransaction } = require("../utils/db");

// 获取用户列表（单部门）
exports.getUserList = async ({
  page = 1,
  pageSize = 10,
  FUsername,
  departmentId,
}) => {
  const offset = (page - 1) * pageSize;
  let sql = `
    SELECT 
      u.FUserId, u.FUsername, u.FEmail, u.FAvatar, u.FIsActive, 
      u.FCreatedAt, u.FUpdatedAt, 
      d.FId AS FDepartmentId, d.FName AS FDepartmentName
    FROM t_users u
    LEFT JOIN t_user_departments ud ON u.FUserId = ud.FUserId
    LEFT JOIN t_departments d ON ud.FDepartmentId = d.FId`;

  let countSql = `
    SELECT COUNT(DISTINCT u.FUserId) as total
    FROM t_users u
    LEFT JOIN t_user_departments ud ON u.FUserId = ud.FUserId`;

  const whereClauses = [];
  const params = [];
  const countParams = [];

  if (FUsername) {
    whereClauses.push("(u.FUsername LIKE ? OR u.FEmail LIKE ?)");
    const searchParam = `%${FUsername}%`;
    params.push(searchParam, searchParam);
    countParams.push(searchParam, searchParam);
  }

  if (departmentId) {
    whereClauses.push("ud.FDepartmentId = ?");
    params.push(departmentId);
    countParams.push(departmentId);
  }

  if (whereClauses.length > 0) {
    const whereStr = " WHERE " + whereClauses.join(" AND ");
    sql += whereStr;
    countSql += whereStr;
  }

  sql += " ORDER BY u.FCreatedAt DESC LIMIT ? OFFSET ?";
  params.push(parseInt(pageSize), parseInt(offset));

  const users = await query(sql, params);
  const [totalResult] = await query(countSql, countParams);

  const processedUsers = users.map((user) => ({
    ...user,
    FIsActive: user.FIsActive === 1, // Convert 0/1 to false/true
    department: user.FDepartmentId
      ? { FId: user.FDepartmentId, FName: user.FDepartmentName }
      : null,
  }));

  return {
    list: processedUsers,
    total: totalResult.total,
    page: parseInt(page),
    pageSize: parseInt(pageSize),
  };
};
/**
 * 获取所有激活用户列表（可选根据用户名模糊查询）
 * @param {Object} [params] - 可选查询参数
 * @param {string} [params.FUsername] - 可选用户名（模糊查询）
 * @returns {Promise<Array>} 用户列表
 */
exports.getActiveUserList = async (params = {}) => {
  // 解构参数并设置默认值
  const { FUsername = "" } = params;

  // 基础SQL查询
  let sql = `
    SELECT 
      u.FUserId, 
      u.FUsername, 
      u.FEmail, 
      u.FAvatar,
      d.FId AS FDepartmentId, 
      d.FName AS FDepartmentName
    FROM t_users u
    LEFT JOIN t_user_departments ud ON u.FUserId = ud.FUserId
    LEFT JOIN t_departments d ON ud.FDepartmentId = d.FId
    WHERE u.FIsActive = 1
  `;

  const queryParams = [];

  // 只有当FUsername有值时才添加查询条件
  if (FUsername && FUsername.trim()) {
    const searchParam = `%${FUsername.trim()}%`;
    sql += ` AND (u.FUsername LIKE ? OR u.FEmail LIKE ?)`;
    queryParams.push(searchParam, searchParam);
  }

  sql += ` ORDER BY u.FUsername ASC`;

  try {
    const users = await query(sql, queryParams);

    return users.map((user) => ({
      FUserId: user.FUserId,
      FUsername: user.FUsername,
      FEmail: user.FEmail,
      FAvatar: user.FAvatar,
      department: user.FDepartmentId
        ? {
            FId: user.FDepartmentId,
            FName: user.FDepartmentName,
          }
        : null,
    }));
  } catch (error) {
    console.error("获取用户列表失败:", error);
    throw new Error("获取用户列表时发生错误");
  }
};
// 创建用户（单部门）
exports.createUser = async (userData) => {
  const {
    FUsername,
    FPassword = "123456",
    FIsActive = 1,
    departmentId,
  } = userData;

  const existingUsers = await query(
    "SELECT FUserId FROM t_users WHERE FUsername = ? LIMIT 1",
    [FUsername]
  );
  if (existingUsers.length > 0) {
    throw { status: 400, message: "用户名已存在" };
  }

  if (departmentId) {
    const [departments] = await query(
      "SELECT FId FROM t_departments WHERE FId = ? LIMIT 1",
      [departmentId]
    );
    if (!departments) {
      throw { status: 400, message: "部门不存在" };
    }
  }

  return withTransaction(async (conn) => {
    const FUserId = uuidv4();
    const hashedPassword = await bcrypt.hash(FPassword, 10);

    await query(
      `INSERT INTO t_users 
       (FUserId, FUsername, FPassword, FIsActive)
       VALUES (?, ?, ?, ?)`,
      [FUserId, FUsername, hashedPassword, FIsActive],
      conn
    );
    console.log("插入", departmentId);

    if (departmentId) {
      await query(
        `INSERT INTO t_user_departments 
         (FUserId, FDepartmentId) 
         VALUES (?, ?)`,
        [FUserId, departmentId],
        conn
      );
    }

    return { FUserId, FUsername, FIsActive, departmentId };
  });
};

// 更新用户信息（单部门）
exports.updateUser = async (userData) => {
  const { FUserId } = userData;
  const existing = await query(
    "SELECT FUserId FROM t_users WHERE FUserId = ? LIMIT 1",
    [FUserId]
  );
  if (!existing.length) {
    throw { status: 400, message: "用户不存在" };
  }

  const { departmentId, ...updateData } = userData;
  const updates = [];
  const params = [];

  const allowedFields = ["FUsername", "FIsActive"];
  allowedFields.forEach((field) => {
    if (updateData[field] !== undefined) {
      updates.push(`${field} = ?`);
      params.push(updateData[field]);
    }
  });

  return withTransaction(async (conn) => {
    if (updates.length > 0) {
      params.push(FUserId);
      await query(
        `UPDATE t_users SET ${updates.join(", ")} WHERE FUserId = ?`,
        params,
        conn
      );
    }

    if (updateData.FPassword) {
      const hashedPassword = await bcrypt.hash(updateData.FPassword, 10);
      await query(
        "UPDATE t_users SET FPassword = ? WHERE FUserId = ?",
        [hashedPassword, FUserId],
        conn
      );
    }

    if (departmentId !== undefined) {
      const [departments] = await query(
        "SELECT FId FROM t_departments WHERE FId = ? LIMIT 1",
        [departmentId],
        conn
      );
      if (!departments) {
        throw { status: 400, message: "部门不存在" };
      }

      await query(
        "DELETE FROM t_user_departments WHERE FUserId = ?",
        [FUserId],
        conn
      );

      await query(
        `INSERT INTO t_user_departments (FUserId, FDepartmentId) VALUES (?, ?)`,
        [FUserId, departmentId],
        conn
      );
    }

    return true;
  });
};

// 获取用户详情（单部门）
exports.getUserById = async (FUserId) => {
  const [users] = await query(
    `SELECT 
     u.FUserId, u.FUsername, u.FEmail, u.FAvatar, u.FIsActive,
     u.FCreatedAt, u.FUpdatedAt,
     d.FId AS FDepartmentId, d.FName AS FDepartmentName
     FROM t_users u
     LEFT JOIN t_user_departments ud ON u.FUserId = ud.FUserId
     LEFT JOIN t_departments d ON ud.FDepartmentId = d.FId
     WHERE u.FUserId = ?
     LIMIT 1`,
    [FUserId]
  );

  if (users.length === 0) {
    throw { status: 400, message: "用户不存在" };
  }

  const [roles] = await query(
    `SELECT r.FId, r.FName 
     FROM t_roles r
     JOIN t_user_roles ur ON r.FId = ur.FRoleId
     WHERE ur.FUserId = ?`,
    [FUserId]
  );

  return {
    ...users[0],
    roles,
    department: users[0].FDepartmentId
      ? { FId: users[0].FDepartmentId, FName: users[0].FDepartmentName }
      : null,
  };
};

// 更新用户状态
exports.updateUserStatus = async (FUserId, FIsActive) => {
  const { affectedRows } = await query(
    "UPDATE t_users SET FIsActive = ? WHERE FUserId = ?",
    [FIsActive, FUserId]
  );

  if (affectedRows === 0) {
    throw { status: 400, message: "用户不存在" };
  }

  if (!FIsActive) {
    await query("UPDATE t_user_tokens SET FIsRevoked = 1 WHERE FUserId = ?", [
      FUserId,
    ]);
  }
};

// 删除用户
exports.deleteUser = async (FUserId) => {
  return withTransaction(async (conn) => {
    await query("DELETE FROM t_user_roles WHERE FUserId = ?", [FUserId], conn);
    await query("DELETE FROM t_user_tokens WHERE FUserId = ?", [FUserId], conn);
    await query(
      "DELETE FROM t_user_login_history WHERE FUserId = ?",
      [FUserId],
      conn
    );
    await query(
      "DELETE FROM t_user_departments WHERE FUserId = ?",
      [FUserId],
      conn
    );

    const { affectedRows } = await query(
      "DELETE FROM t_users WHERE FUserId = ?",
      [FUserId],
      conn
    );

    if (affectedRows === 0) {
      throw { status: 400, message: "用户不存在" };
    }

    return true;
  });
};
